import React, { Component } from 'react';
import { Linking, Platform, StyleSheet, View, Text,Image,Modal, Alert,ScrollView, BackHandler,TouchableOpacity } from 'react-native';
import { NavigationActions } from 'react-navigation';
import { Root } from 'native-base';
import { connect } from 'react-redux';
import Swiper from 'react-native-swiper';
import LinearGradient from 'react-native-linear-gradient';

import Routes from './Routes';
import Config from './config';
import Http from './utils/HttpPost';
import { Colors, Metrics } from './theme';

// 热更新配置
import {
  isFirstTime,
  isRolledBack,
  packageVersion,
  currentVersion,
  checkUpdate,
  downloadUpdate,
  switchVersion,
  switchVersionLater,
  markSuccess,
} from 'react-native-update';

import _updateConfig from '../update.json';
const { appKey } = _updateConfig[Platform.OS];

// 未登录允许的路由
let routerAllow = {
  Login: true,
  Register: true,
  ForgetPassword: true,
  Scanning: true,
  Home: true,
  ServiceAgreement: true,
  PrivacyPolicy: true,
}

class Roots extends Component {
  constructor(props) {
    super(props);
    this.state = {
      updateModalVisible: false,
      hotVersion: '',
      updateContent: '',
      downloadUrl: '',
      hotInfo: {},
      upAppLoading: false,

      noticeModalVisible: false,
      noticeInfoTitle: '温馨提示',
      noticeInfoContent: 'Wubba lubba dub dub!!！'
    }
  }

  // 闪屏触发
  componentDidMount() {
    // this.hotReload();

    // let ignoreVisonList = this.props.ignoreVisonList;
    // if (ignoreVisonList.length) {
    //   if (ignoreVisonList.indexOf(Config.Version.version) == '-1') {
    //     this.checkUpdate();
    //   }
    // } else {
    //   this.checkUpdate();
    // }

    // 获取凭证
    this.getQiniuToken();
  }

  //第一次进入app 
  firstInAppFunc() {
    this.props.setGlobalInfo({ isFirstApp: false })
  }

  //忽略热梗 
  ignoreThisVisonFunc() {
    let ignoreVisonList = this.props.ignoreVisonList;
    this.setState({ updateModalVisible: false }, () => {
      this.props.setGlobalInfo({ ignoreVisonList: ignoreVisonList.push(Config.Version.version) })
    })
  }

  // 忽略公告
  ignoreNoticeFunc() {
    this.setState({ noticeModalVisible: false }, () => {
      this.props.setGlobalInfo({ notiVisible: false })
    })
  }

  // 热更代码写入是否成功
  hotReload() {
    if (isFirstTime) {
      markSuccess()
    } else if (isRolledBack) {
      Alert.alert('提示', '更新失败,版本被回滚！');
    }
  }

  // 执行更新事件
  doUpdate = async () => {
    try {
      this.setState({ upAppLoading: true })
      const hash = await downloadUpdate(this.state.hotInfo);
      this.setState({ upAppLoading: false, noticeModalVisible: false, updateModalVisible: false }, () => {
        switchVersion(hash);
      })
    } catch (err) {
      Alert.alert('提示', '更新时发生异常，请退出重试！');
    }
  };

  // 检测更新
  checkUpdate = async () => {
    if (Config.Env === 'dev') {
      console.log('开发模式，跳过版本更新检查！')
      return;
    }

    let upInfo;
    try {
      upInfo = await checkUpdate(appKey);
    } catch (err) {
      console.warn(err);
      return;
    }

    if (upInfo.expired) {
      Alert.alert('提示', '您的应用有重大更新，请重新下载并安装', [
        {
          text: '确定', onPress: () => {
            upInfo.downloadUrl && Linking.openURL(upInfo.downloadUrl)
            setTimeout(() => {
              BackHandler.exitApp()
            }, 500);
          }
        },
      ]);
    } else if (upInfo.upToDate) {
      // Alert.alert('提示', '您的应用版本已是最新.');
    } else {
      this.setState({ updateModalVisible: true, hotVersion: upInfo.name, updateContent: upInfo.description, hotInfo: upInfo })
    }
  };

  // 获取七牛上传凭证
	getQiniuToken(){
		Http('post',"/user/upQiniuImg", {  
		}).then(res => {
      this.setState({isLoading: false})
			if (res.code === 200) {
        this.props.setGlobalInfo({ qiniuToken: res.data })
			}
		})
	}

  /**
   * 系统更新提示框
   */
  renderUpdateModal() {
    return (
      <Modal visible={this.state.updateModalVisible} onRequestClose={() => { }}>
        <View style={Styles.updateContainer}>
          <View style={[Styles.updateContainer, { position: 'absolute', left: 0, right: 0, top: 0, bottom: 0, backgroundColor: 'black', opacity: 0.3 }]} />
          <View style={Styles.updateHeader}>
            <Image source={require('./asserts/images/root/update_top_bg.png')} resizeMode="contain" style={{ width: Metrics.screenWidth * 0.75, height: Metrics.screenWidth * 0.75 * 0.454, marginTop: -30 }} />
            <View style={{ paddingLeft: 20, paddingRight: 20 }}>
              <Text style={Styles.updateVersion}>{`是否升级到${this.state.hotVersion}版本？`}</Text>
              <Text style={Styles.updateContent}>{this.state.updateContent}</Text>
              <TouchableOpacity onPress={() => this.doUpdate()}>
                <View style={Styles.updateFooter}>
                  <Text style={Styles.updateText}> {`${this.state.upAppLoading ? "更新中..." : "立即更新"}`} </Text>
                </View>
              </TouchableOpacity>
              <TouchableOpacity onPress={() => this.ignoreThisVisonFunc()}>
                <View style={{ height: 36, width: 120, alignSelf: 'center', justifyContent: 'center', alignItems: 'center' }}>
                  <Text style={{ fontSize: 14, color: Colors.C1 }}>忽略更新</Text>
                </View>
              </TouchableOpacity>
            </View>
          </View>
        </View>
      </Modal>
    )
  }

  /**
   * 渲染系统公告Modal
   */
  renderNoticeModal() {
    let notiVisible = this.props.notiVisible;
    return (
      <Modal animationType="fade" transparent visible={this.state.noticeModalVisible && notiVisible && !this.state.updateModalVisible} onRequestClose={() => { }}>
        <View style={{ flex: 1, backgroundColor: "black", opacity: 0.5 }} />
        <View style={{ position: 'absolute', left: 0, right: 0, top: 0, bottom: 0, flex: 1, justifyContent: 'center', alignItems: 'center' }}>
          <View style={{ width: 280, minHeight: 200, borderRadius: 10, backgroundColor: '#FFFFFF' }}>
            <View style={{ marginTop: -35, width: 70, height: 70, borderRadius: 35, alignSelf: 'center', justifyContent: 'center', alignItems: 'center', backgroundColor: '#FFFFFF' }}>
              <Image source={require('./asserts/images/root/logo.png')} style={{ width: 60, height: 60, borderRadius: 30 }} />
            </View>
            <ScrollView contentContainerStyle={{ padding: 10, paddingLeft: 20, paddingRight: 20 }}>
              <Text style={{ textAlign: 'center', fontSize: 16, color: Colors.C1, fontWeight: 'bold' }}>{this.state.noticeInfoTitle}</Text>
              <Text style={{ fontSize: 14, marginTop: 6 }}>
                {this.state.noticeInfoContent}
              </Text>
            </ScrollView>
            <TouchableOpacity onPress={() => this.setState({ noticeModalVisible: false })}>
              <View style={{ marginTop: 6, marginBottom: 10, height: 36, width: 120, borderRadius: 10, backgroundColor: Colors.subject, alignSelf: 'center', justifyContent: 'center', alignItems: 'center' }}>
                <Text style={{ fontSize: 14, color: Colors.bai }}>关闭</Text>
              </View>
            </TouchableOpacity>
            <TouchableOpacity onPress={() => this.ignoreNoticeFunc()}>
              <View style={{ height: 36, width: 120, alignSelf: 'center', justifyContent: 'center', alignItems: 'center' }}>
                <Text style={{ fontSize: 14, color: Colors.C1 }}>不再提示</Text>
              </View>
            </TouchableOpacity>
          </View>
        </View>
      </Modal>
    )
  }

  // 检测路由改变状态
  getActiveRouteName(navigationState) {
    if (!navigationState) {
      return null;
    }
    const route = navigationState.routes[navigationState.index];
    // dive into nested navigators
    if (route.routes) {
      return this.getActiveRouteName(route);
    }
    return route.routeName;
  }


  // 做一些跳转事情
  doDispatchRouterFunc(rName) {
    this.navigator &&
      this.navigator.dispatch(
        NavigationActions.navigate({ routeName: rName })
      );
  }

  render() {
    return (
      <View style={{ flex: 1, backgroundColor: Colors.back }}>
        {this.props.isFirstApp ?
          <View style={{ flex: 1, backgroundColor: Colors.back }}>
            <Swiper autoplay loop={false}
              dot={<View style={{ backgroundColor: 'rgba(0,0,0,.2)', width: 5, height: 5, borderRadius: 4, marginLeft: 3, marginRight: 3, marginTop: 3, marginBottom: 3 }} />}
              activeDot={<View style={{ backgroundColor: Colors.subject, width: 8, height: 8, borderRadius: 4, marginLeft: 3, marginRight: 3, marginTop: 3, marginBottom: 3 }} />}
              paginationStyle={{
                bottom: 200
              }}
            >

              <View style={Styles.slide}>
                <Image resizeMode='stretch' style={Styles.bannerImg} source={require('./asserts/images/root/appFirst1.jpg')} />
                <View style={Styles.slideItem}>
                  <Image source={require('./asserts/images/root/logo.png')} style={{ width: 60, height: 60, borderRadius: 30 }} />
                  <Text style={Styles.slideText1}>拾材 众人拾柴火焰高</Text>
                  <Text style={Styles.slideText2}>悬赏 互助 赚赏金、兼职平台</Text>
                </View>
              </View>

              <TouchableOpacity style={Styles.slide} onPress={() => { }}>
                <Image resizeMode='stretch' style={Styles.bannerImg} source={require('./asserts/images/root/appFirst2.jpg')} />
                <TouchableOpacity style={Styles.slideItem} onPress={() => {
                  this.firstInAppFunc();
                }}
                >
                  <LinearGradient style={[Styles.signInBtn]} colors={[Colors.subjectJbZuo, Colors.subject]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }}>
                    <Text style={{ fontSize: 14, padding: 16, color: Colors.bai }}>立即体验 {this.props.isFirstApp + ''}</Text>
                  </LinearGradient>
                </TouchableOpacity>
              </TouchableOpacity>

            </Swiper>
          </View>
          :
          <Root style={Styles.container}>
            <Routes 
            ref={nav => {
              this.navigator = nav;
            }}
            onNavigationStateChange={(prevState, currentState, action) => {
                const currentRouteName = this.getActiveRouteName(currentState);
                // 路由拦截器
                if (!this.props.isLogged && !routerAllow[currentRouteName]) {
                  this.doDispatchRouterFunc('Login')
                }
            }} />
            {this.renderUpdateModal()}
            {this.renderNoticeModal()}
          </Root>
        }
      </View>
    )
  }
}

const mapStateToProps = state => ({
  ignoreVisonList: state.global.ignoreVisonList,
  notiVisible: state.global.notiVisible,
  isFirstApp: state.global.isFirstApp,
  isLogged: state.user.isLogged,
});

const mapDispatchToProps = dispatch => ({
  setGlobalInfo: globalInfo => dispatch({ type: 'SET_GLOBALINFO', payload: { globalInfo } }),
});

export default connect(mapStateToProps, mapDispatchToProps)(Roots);


const Styles = StyleSheet.create({
  container: { backgroundColor: Colors.back, flex: 1 },
  updateContainer: { flex: 1, justifyContent: 'center', alignItems: 'center' },
  updateHeader: { width: Metrics.screenWidth * 0.75, backgroundColor: '#FFFFFF', borderRadius: 10 },
  updateVersion: { fontSize: 17, textAlign: 'left', marginTop: 20 },
  updateContent: { fontSize: 14, paddingTop: 15 },
  updateFooter: { marginTop: 15, marginBottom: 15, justifyContent: 'center', alignItems: 'center', alignSelf: 'center', height: 38, width: 180, backgroundColor: '#896aea', borderRadius: 19 },
  updateText: { fontSize: 14, color: '#FFFFFF' },
  slide: { flex: 1 },
  slideItem: { justifyContent: 'center', alignItems: 'center', height: 186, padding: 18 },
  bannerImg: { flex: 1, width: Metrics.screenWidth, height: Metrics.screenHeight - 186 },
  slideText1: { fontSize: 18, marginTop: 8 },
  slideText2: { fontSize: 16, marginTop: 8 },
  signInBtn: { width: Metrics.screenWidth * 0.6, alignItems: "center", borderRadius: 8 },
});
